﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MiniFox.Infrastructure;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Platform.Resources;
using MiniFox.Web;

namespace MiniFox.Platform.Applications.Web.Filters
{
    /// <summary>
    /// OAuth 2 鉴权客户端
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class UserAuthorizationFilter : AuthorizationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        protected UserAuthClient Client { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override AuthorizationClient CreateAuthClient(HttpContext httpContext)
        {
            Client = httpContext.GetAuthClient<UserAuthClient>();
            return Client;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationFilterContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest()) //ajax请求响应json报文并告之未授权
            {
                string code = ResErrorCode.ERR_Unauthorized;
                string msg = ResMessage.ERR_Unauthorized;
                filterContext.Result = new JsonResult(new Response() { Code = code, Message = msg });
            }
            else //非ajax请求直接响应302
            {
                //获取当前路径
                string fullRawUrl = filterContext.HttpContext.Request.GetDisplayUrl();
                //以当前路径为回跳地址，创建跳转地址
                string redirectUrl = Client.GetAuthUrl(new Uri(fullRawUrl)).ToString();
                filterContext.Result = new RedirectResult(redirectUrl);
            }
        }
    }
}
